import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import { getToken, IsNeedBeginRefreshToken, removeAllToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 35000 // request timeout
})

let deviceId = store.getters.deviceId
// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    if (store.getters.token || getToken()) {
      // let each request carry token
      // ['Authorization'] is a custom headers key
      // please modify it according to the actual situation
      let token = getToken()
      if (!token) {
        token = store.getters.token
      }
      config.headers['Authorization'] = 'bearer ' + token
    }
    if (!deviceId || deviceId.length <= 0) {
      // store.dispatch('app/getDeviceId')
      deviceId = store.getters.deviceId
    }
    config.headers['deviceId'] = deviceId
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)
// 为了避免网络请求错误，多次弹出错误提示，在有错误提示的情况下，不再弹出其他错误提示
let synctip = 0
// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    // 刷新token
    refTkn()
    const res = response.data
    let code = 500
    if (res.code) {
      code = parseInt(res.code)
    } else {
      // 如果请求结果中没有code 返回值，交给调用层处理
      return res
    }

    // if the custom code is not 200, it is judged as an error.
    if (code < 200 || code > 299) {
      if (code === 401 && (store.getters.token || getToken())) {
        tryRefTkn()
      } else {
        Message({
          message: res.msg || 'Error',
          type: 'error',
          duration: 5 * 1000
        })
        return Promise.reject(new Error(res.msg || 'Error'))
      }
    } else {
      return res
    }
  },
  error => {
    if (error && error.response && error.response.status === 401 && (store.getters.token || getToken())) {
      // to re-login
      tryRefTkn()
    } else {
      console.log('err' + error) // for debug
      let errmsg = '网络异常'
      if (error && error.response && error.response.status === 404) {
        errmsg = '404：未找到请求资源或服务器升级中,请稍后再试'
      } else if (error && error.response && error.response.status === 500) {
        errmsg = '服务器端异常，请稍后再试：500'
      }
      if (synctip <= 0) {
        synctip = 1
        Message({
          message: errmsg || error.message,
          type: 'error',
          duration: 4 * 1000
        })
        setTimeout(() => { synctip = 0 }, 2000)
      }

      return Promise.reject(error)
    }
  }
)
// 自动刷新 token
const refTkn = function() {
  // 在有token，并且在需要刷新token的情况下，才去刷新token
  if (store.getters.token || getToken()) {
    if (IsNeedBeginRefreshToken()) {
      store.dispatch('user/refreshToken').then(res => {
      }).catch(() => {
        console.log('auto refresh fail')
        // location.reload()
      })
    }
  }
}
/**
 * 尝试刷新token
 */
const tryRefTkn = function() {
  // to re-login
  store.dispatch('user/refreshToken').then((res) => {
    location.reload()
    return
  }).catch((e) => {
    console.log('刷新token失败', e)
    removeAllToken()
    location.reload()
  })
}

export default service
